import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 
 * @author pfister
 * 
 */
public class ClientSocket {
	
	private String hostname;
	private int serverPort;

	private PrintWriter out;
	//private BufferedReader in_;
	private Socket socket;
	
	
	
	public Socket getSocket() {
		return socket;
	}



	public ClientSocket(String host, int port) {
		super();
		this.hostname = host;
		this.serverPort = port;
	}

	
	
	public void init() throws UnknownHostException, IOException {
		socket = new Socket(hostname, serverPort);
		System.out.println("Connected to server");
		//in_ = new BufferedReader(new InputStreamReader(
				//socket.getInputStream()));
		out = new PrintWriter(socket.getOutputStream(), true); // autoflush
	}

	public void end() throws InterruptedException, IOException {
		System.out.println("closing connection - terminated");
		//if (in_ != null)
		//	in_.close();
		if (out != null)
			out.close();
	}

	public void send(String cmd)  {
		try {
			//return 
					doSend(cmd);
		} catch (Exception e) {
			e.printStackTrace();
			//return "error";
		}
	}
	
	private void doSend(String cmd) throws InterruptedException, IOException {
	//	String result = null;
		if (socket.isClosed()) {
			System.out.println("server is down");
			//return result;
		}
		out.println(cmd);
		//result = in_.readLine();
		/*
		if (result == null) 
			System.out.println("server is down");
		 else
		    System.out.println(result);*/
		//return result;
	}

}
